package com.jfeat.am.module.wegou.services.patch.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jfeat.am.module.shopping.services.domain.model.ShoppingCartModel;
import com.jfeat.am.module.shopping.services.persistence.dao.ShoppingCartMapper;
import com.jfeat.am.module.shopping.services.persistence.model.ShoppingCart;
import com.jfeat.am.module.social.services.crud.service.MemberCareService;
import com.jfeat.am.module.social.services.persistence.model.MemberCare;
import com.jfeat.am.module.viewhistory.services.persistence.dao.ViewHistoryMapper;
import com.jfeat.am.module.viewhistory.services.persistence.model.ViewHistory;
import com.jfeat.am.module.wegou.api.patch.ProductStatus;
import com.jfeat.am.module.wegou.api.patch.RestaurantStatus;
import com.jfeat.am.module.wegou.services.domain.model.ViewHistoryModel;
import com.jfeat.am.module.wegou.services.patch.WeGouPatchService;
import com.jfeat.am.module.wegou.services.persistence.dao.MemberMapper;
import com.jfeat.am.module.wegou.services.persistence.dao.ProductMapper;
import com.jfeat.am.module.wegou.services.persistence.dao.ProductStoreMapper;
import com.jfeat.am.module.wegou.services.persistence.dao.RestaurantTagMapper;
import com.jfeat.am.module.wegou.services.persistence.model.Member;
import com.jfeat.am.module.wegou.services.persistence.model.Product;
import com.jfeat.am.module.wegou.services.persistence.model.ProductStore;
import com.jfeat.am.module.wegou.services.persistence.model.RestaurantTag;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Code Generator on 2018-01-03
 */
@Service
public class WeGouPatchServiceImpl implements WeGouPatchService {


    @Resource
    RestaurantTagMapper restaurantTagMapper;
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductStoreMapper productStoreMapper;
    @Resource
    MemberCareService memberCareService;
    @Resource
    ViewHistoryMapper viewHistoryMapper;
    @Resource
    ShoppingCartMapper shoppingCartMapper;
    @Resource
    MemberMapper memberMapper;


    /**
     *  我的店铺
     * */


    /**
     * 浏览记录列表  Json对象  作为 函数使用
     */
    public ViewHistoryModel showViewHistory(long id) {
        ViewHistory viewHistory = viewHistoryMapper.selectById(id);
        JSONObject Obj = JSON.parseObject(JSON.toJSONString(viewHistory));

        //  浏览店铺的信息
        ProductStore restaurant = productStoreMapper.selectById(viewHistory.getRolesId());

        Obj.put("restaurant", restaurant);

        ViewHistoryModel model = JSON.parseObject(JSON.toJSONString(Obj), ViewHistoryModel.class);
        return model;
    }


    /**
     * 产品上下架  当产品为 上(下)架 的时候， 点击事件为 下架
     */
    @Override
    public Integer riseOrDownProduct(long id) {
        Product product = productMapper.selectById(id);
        if ((product.getStatus().compareTo(ProductStatus.RISE.toString()) == 0)) {
            product.setStatus(ProductStatus.DOWN.toString());
        } else {
            product.setStatus(ProductStatus.RISE.toString());
        }
        return productMapper.updateById(product);
    }

    /**
     * / 料理店铺上下架  当产品为 上(下)架 的时候， 点击事件为 下架
     */
    @Override
    public Integer riseOrDownRestaurant(long id) {
        ProductStore restaurant = productStoreMapper.selectById(id);
        if ((restaurant.getStatus().compareTo(RestaurantStatus.RISE.toString()) == 0)) {
            restaurant.setStatus(ProductStatus.DOWN.toString());
        } else {
            restaurant.setStatus(ProductStatus.RISE.toString());
        }
        return productStoreMapper.updateById(restaurant);
    }


    /**
     * 删除多个 Product
     */

    @Override
    public Integer batchDeleteProduct(Long userId, List<Long> ids) {
        Integer affect = productMapper.deleteBatchIds(ids);
        return affect;
    }


    /**
     * 多个添加 TagManage
     */

    @Override
    public Integer batchAddTag(long resId, List<Long> ids) {
        int affect = 0;
        // 先 抹去所有的 记录  然后重新 进行插入操作
        List<RestaurantTag> tags = restaurantTagMapper.selectList(new EntityWrapper<RestaurantTag>().eq("store_id",resId));
        if (tags==null || tags.size()==0){

        }
        for(RestaurantTag tag : tags){
            productStoreMapper.deleteById(tag.getId());
        }
        if (ids==null|| ids.size()==0){
            return ids.size();
        }

        for (Long id : ids) {
            RestaurantTag restaurantTag = new RestaurantTag();
            restaurantTag.setStoreId(resId);
            restaurantTag.setTagId(id);
            RestaurantTag tag = restaurantTagMapper.selectOne(restaurantTag);
            if (tag == null) {
                restaurantTagMapper.insert(restaurantTag);
                affect++;
            } else {
                // do nothing
            }
        }
        return affect;
    }

    /**
     * 将料理店铺设置为 禁止登陆 或 正常 状态 (正常 -> 禁止登陆  禁止登陆 ->  正常)
     */
    @Override
    public Integer setRestaurantAsProhibitionOrDown(long resId) {
        ProductStore restaurant = productStoreMapper.selectById(resId);
        if (restaurant.getStatus().compareTo(RestaurantStatus.LOGINPROHIBITION.toString()) == 0) {
            restaurant.setStatus(RestaurantStatus.DOWN.toString());
        } else {
            restaurant.setStatus(RestaurantStatus.LOGINPROHIBITION.toString());
        }
        return productStoreMapper.updateById(restaurant);
    }

    /**
     * 关注列表  当用户进入料理店铺详情的时候 自动插入一条数据
     */
    @Override
    public Integer insertCare(long userId, long resId) {
        Integer result = 0;
//        判断是否已经关注
        List<MemberCare> memberCares = memberCareService.queryMemberCareByUserIdAndFollowedId(resId, userId);
        if (memberCares.size() == 0){
            MemberCare memberCare = new MemberCare();
            memberCare.setFollowTime(new Date());
            memberCare.setFollowerId(userId);
            memberCare.setMemberId(resId);
            // 设置角色为游客
            memberCare.setRoles("TOURIST");
            result = memberCareService.createMaster(memberCare);
        }
        return result;
    }


    /*
    *   用户的浏览足迹 插入足迹 如果存在了浏览记录，则更新 时间 没有记录 则插入 主要是 浏览的 料理店的足迹
    * */

    @Override
    public Integer insertViewHistory(long userId, long resId) {
        ViewHistory originViewHistory = new ViewHistory();
        originViewHistory.setMemberId(userId);
        originViewHistory.setRolesId(resId);
        originViewHistory.setRoles("RESTAURANT");
        ViewHistory viewHistory = viewHistoryMapper.selectOne(originViewHistory);
        if (viewHistory != null) {
            viewHistory.setViewTime(new Date());
            return viewHistoryMapper.updateById(viewHistory);
        } else {
            originViewHistory.setViewTime(new Date());
            return viewHistoryMapper.insert(originViewHistory);
        }
    }


    /**
     * 浏览列表 包括 浏览的店铺或者料理店的信息
     */
    @Override
    public List<ViewHistoryModel> viewHistories(Page<ViewHistoryModel> page, long userId) {

        List<ViewHistoryModel> models = new ArrayList<>();
        //  找出改表中属于自己的所有的记录
        List<ViewHistory> viewHistories = viewHistoryMapper.selectPage(page,
                new EntityWrapper<ViewHistory>().eq("member_id", userId).orderBy(ViewHistory.VIEW_TIME, false));
        if (viewHistories == null || viewHistories.size() == 0) {
            return null;
        } else {
            for (ViewHistory viewHistory : viewHistories) {
                ViewHistoryModel model = showViewHistory(viewHistory.getId());
                models.add(model);
            }
            return models;
        }
    }

    /**
     * 关注列表 访问详情的时候 自动插入一条数据
     */
    public Integer memberCareRes(long resId, long userId) {

        Member member = new Member();
        member.setUserId(userId);
        if (memberMapper.selectOne(member) != null) {
            MemberCare memberCare = new MemberCare();
            memberCare.setMemberId(userId);
            memberCare.setFollowerId(resId);
            memberCare.setRoles("RESTAURANT");
            memberCare.setFollowTime(new Date());
            return memberCareService.createMaster(memberCare);
        } else {
            return null;
        }
    }

    /**
     * 购物车
     */

    @Override
    public Integer addProductToCart(long resId, long userId, List<ShoppingCartModel> models) {

        int affect = 0;
        for (ShoppingCartModel model : models) {
            ShoppingCart cart = new ShoppingCart();
            cart.setUserId(userId);
            Product product = productMapper.selectById(model.getProId());
            cart.setCreatedDate(new Date());
            cart.setProductId(model.getProId());
            cart.setFareId(resId);
            cart.setProductName(product.getName());
            cart.setCover(product.getCover());
            cart.setTotalPrice(BigDecimal.valueOf(model.getQuantity() * product.getPrice().doubleValue()));
            shoppingCartMapper.insert(cart);
            affect++;
        }

        // 返回 影响条数
        return affect;
    }

}
